<?php

	class Array2XML
	{

		private $version = '1.0';
		private $encoding = 'UTF-8';
		private $rootName = 'Root';
		private $by_attributes = false;

		public function convert($data)
		{
			$writer = new XMLWriter();

			$writer->openMemory();
			$writer->startDocument($this->version, $this->encoding);
			$writer->startElement($this->rootName);
			if (is_array($data)) {
				$this->getXML($data, $writer);
			}
			$writer->endElement();
			return $writer->outputMemory();
		}

		public function setVersion($version)
		{
			$this->version = $version;
		}

		public function setEncoding($encoding)
		{
			$this->encoding = $encoding;
		}

		public function setRootName($rootName)
		{
			$this->rootName = $rootName;
		}

		public function setByAttributes($state)
		{
			$this->by_attributes = (bool)$state;
		}

		public function getXML($data, &$writer = null)
		{
			$writer = is_null($writer) ? new XMLWriter() : $writer;

			$newElement = array();
			if (is_array($data) || is_object($data)) {
				foreach ($data as $key => $val) {
					if (!is_array($val) && !is_object($val)) {
						if (is_numeric($key)) {
							$key = 'Row';
						}
						if ($this->by_attributes) {
							$writer->writeAttribute($key, $val);
						} else {
							$writer->writeElement($key, $val);
						}
					} else {
						$newElement[$key] = $val;
					}
				}

				foreach ($newElement as $key => $val) {
					if (is_numeric($key)) {
						$key = 'row';
					}
					$writer->startElement($key);
					$this->getXML($val, $writer);
					$writer->endElement();
				}
			} else {
				is_bool($data) && $data = $data ? 'true' : 'false';
				$writer->text($data);
			}

		}
	}